import java.util.*;

/**
 * @author LKQ
 * @date 2022/5/8 20:55
 * @description 动态规划
 */
public class Solution2 {
    public static void main(String[] args) {

    }

    public int minPathSum(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        // dp[i][j]代表到达 i,j 位置的最短长度
        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 && j == 0) {
                    dp[i][j] = grid[i][j];
                } else {
                    // 从上向下移动而来
                    int top = i - 1 >= 0 ? dp[i - 1][j] + grid[i][j] : Integer.MAX_VALUE;
                    // 从左向右移动而来
                    int left = j - 1 >= 0 ? dp[i][j-1] + grid[i][j] : Integer.MAX_VALUE;
                    // 两者取最小
                    dp[i][j] = Math.min(top, left);
                }
            }
        }
        return dp[m - 1][n - 1];
    }
}
